#!/usr/bin/perl
# 2014/01/28 Change to read tsv file format
# 2011/02/05 Background ratio calculation

use strict;
use warnings;
use IO::File;
use Getopt::Std;
use Carp qw(croak);
$| = 0;

if(@ARGV != 6 or $ARGV[0] eq '--help'){
	die "Usage : $0 -s [sample directory] -c [control directory] -o [output file]\n";
}

my $Window_size = 1000;	# window size


my %opt;
getopts("s:c:o:", \%opt);
my $DIR_sample = $opt{s};
my $DIR_control = $opt{c};
my $FILE_output = $opt{o};

my %map_sample = &readMap($DIR_sample);
my %map_control = &readMap($DIR_control);
sub readMap{
	my ($directory) = @_;
	my %hash;
	foreach my $chr(qw(I II III)){
	    my $file = sprintf "%s/%s.tags.tsv", $directory, $chr;
		my $fh = IO::File->new($file) or die "cannot open $file: $!";
		while($_ = $fh->getline()){
			s/\r?\n//;
			### TSV format
			my ($none, $chr, $pos, $direction, $tags, $length) = split /\t/;

			### only consider + strand
			if($direction == 1){
				next;
			}

			my $cate = &categorize($pos);
			$hash{"$chr:$cate"} += $tags;
		}
		$fh->close();
	}
	return %hash;
}


### calculate reads in each window
my $fh_out = IO::File->new($FILE_output, 'w') or die "cannot write $FILE_output: $!";
$fh_out->print("Control\tSample\n");
foreach my $key(keys %map_control){
	unless(exists $map_sample{$key}){
		next;
	}
	$fh_out->printf("%d\t%d\n", $map_control{$key}, $map_sample{$key});
}
$fh_out->close();

sub categorize{
	my ($value) = @_;
	my $category = int($value / $Window_size);
	return $category;
}